--[[
	滑动列表
]]
local M = {}

function M.newScrollList(params)
	local isDebug = params.isDebug
	local totalMember = params.totalMember
	local drawViewG = params.drawViewG
	local addY = params.addY or 15
	local outRows = params.outRows or 3
	local height = params.height
	local halfHeight = params.height/2

	local mMin = math.min
	local tItems = {}

	local gList
	local view
	-- touch事件监听
	local function onTouch(event)
		if event.phase == "moved" then
			if event.direction == "up" then
				local totalItems = #tItems
				local gItem = tItems[totalItems - 3]

				if gItem then
					-- -- 将gItem的坐标转化为gList中的坐标
					local itemY = view.y + gItem.y

					if itemY < height then
						if totalItems < totalMember then
							for index = totalItems + 1, mMin(totalMember, totalItems + outRows) do
								gList:addItem(index)
							end
						end		
					end
				end
			end
		end
	end

	gList = widget.newScrollView({
		top = params.top,
		left = params.left,
		width = params.width,
		height = params.height,
		hideScrollBar = true,
		friction = 0.88,
		horizontalScrollDisabled = true,
		verticalScrollDisabled = false,
		listener = onTouch,
		backgroundColor = isDebug and {0.9, 0.9, 0.9, 0.7},
		hideBackground = not isDebug,
	})
	view = gList:getView()

	function gList:addItem(index)
		local gItem = drawViewG(index, gList)

		gList:insert(gItem)

		if index == 1 then
			gItem.y = 0
		else
			gItem.y = tItems[index - 1].y + tItems[index - 1].height + addY
		end

		tItems[index] = gItem
	end

	local function init()
		local outIndex = 0
		for i = 1, totalMember do
			gList:addItem(i)
			local viewHeight = view.height

			-- 当超出屏幕后不画
			if viewHeight > params.height then
				if outIndex == 0 then
					outIndex = i
				else
					if i >= outIndex + outRows then
						break
					end
				end
			end
		end
	end
	init()

	return gList
end

return M